package com.gwnet.demo.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONObject;
import com.gwnet.common.core.domain.ResponseResult;
import com.gwnet.common.core.utils.ValidatorUtils;
import com.gwnet.common.core.validate.AddGroup;
import com.gwnet.common.core.validate.EditGroup;
import com.gwnet.common.core.validate.QueryGroup;
import com.gwnet.common.excel.core.ExcelResult;
import com.gwnet.common.excel.utils.ExcelUtil;
import com.gwnet.common.idempotent.annotation.RepeatSubmit;
import com.gwnet.common.log.annotation.Log;
import com.gwnet.common.log.enums.BusinessType;
import com.gwnet.common.mybatis.core.page.PageQuery;
import com.gwnet.common.mybatis.core.page.TableDataInfo;
import com.gwnet.common.satoken.utils.LoginHelper;
import com.gwnet.common.web.core.BaseController;
import com.gwnet.demo.domain.TestDemo;
import com.gwnet.demo.domain.bo.TestDemoBo;
import com.gwnet.demo.domain.bo.TestDemoImportVo;
import com.gwnet.demo.domain.vo.TestDemoVo;
import com.gwnet.demo.service.ITestDemoService;
import com.gwnet.system.api.model.LoginUser;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 测试单表Controller
 * @author CHENGPENG
 * @date 2021-07-26
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/demo")
public class TestDemoController extends BaseController {

    private static final Logger log = LoggerFactory.getLogger(TestDemoController.class);
    @Resource
    private final ITestDemoService iTestDemoService;

    @Log(title = "测试接口请求", businessType = BusinessType.OTHER)
    @PostMapping( value = "/test")
    public ResponseResult test(@RequestBody JSONObject jsonParams ){
        log.info("test:测试接口请求.....");
        try{
            log.info("请求参数为：{}",jsonParams.toJSONString());
            //根据Token获得基本信息，用于用户操作权限校验
            /**
             * 根据Token获得基本信息，用于用户操作权限校验
             * 1、操作人ID、操作人姓名 信息从Token中获取。
             * 2、若Token校验不通过，则返回失败
             * */
            LoginUser loginUser = LoginHelper.getLoginUser();
            if (loginUser != null && !loginUser.getMenuPermission().isEmpty()){
                log.info("哈合...我被访问了......");
                return ResponseResult.success();
            }else {
                log.info("权限验证失败，");
                return ResponseResult.failure();
            }
        }catch (Exception e){
            e.printStackTrace();
            log.error("请求失败：{}",e.getMessage());
            return ResponseResult.failure();
        }
    }

    /**
     * 查询测试单表列表
     */
    @SaCheckPermission("demo:demo:list")
    @GetMapping("/list")
    public ResponseResult list(TestDemoBo bo, PageQuery pageQuery) {
        TableDataInfo<TestDemoVo> testDemoVoTableDataInfo = iTestDemoService.queryPageList(bo, pageQuery);
        return ResponseResult.success(testDemoVoTableDataInfo);
    }

    /**
     * 自定义分页查询
     */
    @SaCheckPermission("demo:demo:list")
    @GetMapping("/page")
    public TableDataInfo<TestDemoVo> page(@Validated(QueryGroup.class) TestDemoBo bo, PageQuery pageQuery) {
        return iTestDemoService.customPageList(bo, pageQuery);
    }

    /**
     * 导入测试-校验
     *
     * @param file 导入文件
     */
    @Log(title = "测试单表", businessType = BusinessType.IMPORT)
    @SaCheckPermission("demo:demo:import")
    @PostMapping(value = "/importData", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResponseResult importData(@RequestPart("file") MultipartFile file) throws Exception {
        ExcelResult<TestDemoImportVo> excelResult = ExcelUtil.importExcel(file.getInputStream(), TestDemoImportVo.class, true);
        List<TestDemoImportVo> volist = excelResult.getList();
        List<TestDemo> list = BeanUtil.copyToList(volist, TestDemo.class);
        iTestDemoService.saveBatch(list);
        return ResponseResult.success(excelResult.getAnalysis());
    }

    /**
     * 导出测试单表列表
     */
    @SaCheckPermission("demo:demo:export")
    @Log(title = "测试单表", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(@Validated TestDemoBo bo, HttpServletResponse response) {
        List<TestDemoVo> list = iTestDemoService.queryList(bo);
        // 测试雪花id导出
//        for (TestDemoVo vo : list) {
//            vo.setId(1234567891234567893L);
//        }
        ExcelUtil.exportExcel(list, "测试单表", TestDemoVo.class, response);
    }

    /**
     * 获取测试单表详细信息
     *
     * @param id 测试ID
     */
    @SaCheckPermission("demo:demo:query")
    @GetMapping("/{id}")
    public ResponseResult getInfo(@NotNull(message = "主键不能为空") @PathVariable("id") Long id) {
        TestDemoVo testDemoVo = iTestDemoService.queryById(id);
        return ResponseResult.success(testDemoVo);
    }

    /**
     * 新增测试单表
     */
    @SaCheckPermission("demo:demo:add")
    @Log(title = "测试单表", businessType = BusinessType.INSERT)
    @RepeatSubmit(interval = 2, timeUnit = TimeUnit.SECONDS, message = "{repeat.submit.message}")
    @PostMapping()
    public ResponseResult add(@RequestBody TestDemoBo bo) {
        // 使用校验工具对标 @Validated(AddGroup.class) 注解
        // 用于在非 Controller 的地方校验对象
        ValidatorUtils.validate(bo, AddGroup.class);
        return ResponseResult.success(iTestDemoService.insertByBo(bo));
    }

    /**
     * 修改测试单表
     */
    @SaCheckPermission("demo:demo:edit")
    @Log(title = "测试单表", businessType = BusinessType.UPDATE)
    @RepeatSubmit
    @PutMapping()
    public ResponseResult edit(@Validated(EditGroup.class) @RequestBody TestDemoBo bo) {
        return ResponseResult.success(iTestDemoService.updateByBo(bo));
    }

    /**
     * 删除测试单表
     *
     * @param ids 测试ID串
     */
    @SaCheckPermission("demo:demo:remove")
    @Log(title = "测试单表", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public ResponseResult remove(@NotEmpty(message = "主键不能为空") @PathVariable Long[] ids) {
        return ResponseResult.success(iTestDemoService.deleteWithValidByIds(Arrays.asList(ids), true));
    }
}
